/*******************************************************************************
 * Copyright (c) 2009 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *     Ali Ok (www.aliok.info) - initial API and implementation
 *******************************************************************************/
package org.eclipse.team.internal.search;

import java.util.ArrayList;
import java.util.WeakHashMap;

import org.eclipse.core.runtime.ListenerList;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.search.ui.ISearchQuery;
import org.eclipse.search.ui.ISearchResult;
import org.eclipse.search.ui.ISearchResultListener;
import org.eclipse.search.ui.SearchResultEvent;
import org.eclipse.team.core.history.IFileHistory;
import org.eclipse.team.core.history.IFileRevision;

public final class SearchResult implements ISearchResult {
	private SearchQuery query;
	
	private final ArrayList<IFileRevision> results = new ArrayList<IFileRevision>();
	private final WeakHashMap<IFileRevision, IFileHistory> histories = new WeakHashMap<IFileRevision, IFileHistory>();

	private final ListenerList listeners = new ListenerList();
	
	public SearchResult(SearchQuery cvsQuery) {
		this.query = cvsQuery;
	}

	public void addListener(ISearchResultListener l) {
		listeners.add(l);
	}

	public ImageDescriptor getImageDescriptor() {
		// TODO Auto-generated method stub
		return null;
	}

	public String getLabel() {
		// TODO: externalize
		return "commits";
	}

	public ISearchQuery getQuery() {
		return query;
	}

	public String getTooltip() {
		// TODO: externalize
		return "Commits Tooltip";
	}

	public void removeListener(ISearchResultListener l) {
		listeners.remove(l);
	}

	public ArrayList<IFileRevision> getResult() {
		//TODO: this should be unmodifiable
		return results;
	}

	public void add(IFileRevision fileRevision, IFileHistory history) {
		results.add(fileRevision);
		histories.put(fileRevision, history);
		//TODO: extract method
		Object[] oListeners =  listeners.getListeners();
		//TODO: more usable events
		SearchResultEvent sre = new SearchResultEvent(this) {
			private static final long serialVersionUID = -4033648093546820133L;
		};
		for (int i = 0; i < oListeners.length; i++) {
			((ISearchResultListener) oListeners[i]).searchResultChanged(sre);
		}
	}

	public void removeAllListeners() {
		listeners.clear();
	}
	
	// TODO: remove this from here
	// it is not clean design
	public IFileRevision getPreviousFileRevision(IFileRevision current){
		IFileHistory fh = histories.get(current);
		if(fh == null){
			return null;
		}
		IFileRevision[] fr = fh.getContributors(current);
		if(fr.length == 0){
			return null;
		}
		return fr[0]; 
	}
}